package org.yinxue.swing.im.client;

import com.google.common.eventbus.Subscribe;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.yinxue.swing.im.domain.event.MessageSendEvent;
import reactor.core.publisher.Flux;

import java.time.Duration;

public class IMClient {

    private Channel[] channels = new Channel[1];

    public IMClient connectServer() {
        new Thread(() -> {
//            while(true){
            Bootstrap b = new Bootstrap()
                    .group(new NioEventLoopGroup())
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ClientHandler());
            connect(b);
//            }
        }).start();
        return this;
    }

    @Subscribe
    public void sendMessage(MessageSendEvent event) {
        channels[0].writeAndFlush(((MessageSendEvent) event).getMessage());
    }

    private void connect(Bootstrap b) {
        try {
            ChannelFuture f = b.connect("10.5.12.100", 8096).sync();
            f.addListener(future -> Flux.interval(Duration.ofSeconds(5)).subscribe(l -> f.channel().writeAndFlush("GET\n")));
            System.out.println("客户端启动..");
            channels[0] = f.channel();
            System.out.println("client通道:" + channels[0].toString());
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                // 延迟3s再进行注册
                Thread.sleep(3000L);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
            connect(b);
        }
    }
}
